package com.hx.generic;

import java.util.Arrays;

public class DynamicArray<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;

    public DynamicArray() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    private void ensureCapacity(int miniCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity >= miniCapacity) {
            return;
        }
        int newCapacity = oldCapacity * 2 + 2;
        if (newCapacity < miniCapacity) {
            newCapacity = miniCapacity;
        }
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    public void add(E e) {
        ensureCapacity(size + 1);
        elementData[++size] = e;
    }

    public E get(int index) {
        return (E) elementData[index];
    }

    private int size() {
        return size;
    }

    public E set(int index, E element) {
        E oldValue = get(index);
        elementData[index] = element;
        return oldValue;
    }

    public static void main(String[] args) {
        DynamicArray<Integer> dynamicArray = new DynamicArray<>();
        dynamicArray.add(1);
    }
}
